#!/usr/bin/env python
# Copyright (c) 2009, Purdue University
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# Redistributions of source code must retain the above copyright notice, this
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Remote BIND Version Checker for Roster"""

__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '0.18'


import sys
import shutil
import os

from fabric import api as fabric_api
from fabric import state as fabric_state
from fabric import network as fabric_network
from optparse import OptionParser

import ConfigParser
import roster_core
from roster_core import constants

def CheckBINDVersion(ssh_port, ssh_id, user_name, dns_server):
  """Checks the remote's server version of BIND
  Inputs:
    ssh_port: port to use over SSH
    ssh_id: id file to use over SSH	
    user_name: the username to use over SSH
    dns_server: string of ip address or hostname of DNS serveri

  Output: output of "named -v" (ex. 'BIND 9.9.0')
  """

  EXEC = 'named -v'
  dns_server_sets = None
  ssh_command_parts = []

  ssh_command_parts.append('%s@' % user_name)
  ssh_command_parts.append(dns_server)
  ssh_command_parts.append(':%s' % ssh_port)
  ssh_command_string = ''.join(ssh_command_parts)

  print 'Connecting to "%s"' % dns_server

  try:
    if( ssh_id ):
      fabric_api.env.key_filename = ssh_id
    fabric_api.env.warn_only = True

    fabric_state.output['running'] = False
    fabric_state.output['warnings'] = False
    fabric_api.env.host_string = ssh_command_string

    #The result of 'named -v' will be "BIND X.Y.Z*"
    #So we return "X.Y.Z"
    return fabric_api.run(EXEC).strip('BIND ')[:5]

  finally:
    fabric_network.disconnect_all()

def main(args):	
  """Collects command line arguments. Exports tree.
  Inputs:
    args: list of arguments from the command line	
  """
  usage = ('\n'
           '\n'
           'To check DNS server\'s BIND software version:\n'
           '\t%s --hostname <hostname> [-p <ssh-port>]\n'
           '\t[-c <config-file>] [-u <ssh-username>] [-i <ssh-id file>]\n' % sys.argv[0])

  parser = OptionParser(version='%%prog (Roster %s)' % __version__, usage=usage)
  parser.add_option('-c', '--config-file', action='store', dest='config_file',
                    help='Config File Location', metavar='<config-file>',
                    default=constants.SERVER_CONFIG_FILE_LOCATION)
  parser.add_option('-s', '--ssh-user-name', action='store', dest='ssh_username',
                    help='SSH username.', metavar='<ssh-user-name>',
                    default='root')
  parser.add_option('-p', '--ssh-port', action='store', dest='ssh_port',
                    help='SSH port number.', metavar='<ssh-port>',
                    default=22)
  parser.add_option('-i', '--ssh-id', action='store', dest='ssh_id',
                    help='SSH id file.', metavar='<ssh-id>',
                    default=None)
  parser.add_option('-u', '--core-user-name', action='store', dest=u'core_username',
                    help='Roster Core User Name', metavar='<core-user-name>',
                    default=None)

  (globals()["options"], args) = parser.parse_args(args)

  if( options.core_username is None ):
    print 'A Roster Core username must be provided'
    sys.exit(1)

  config_instance = roster_core.Config(options.config_file)
  core_instance = roster_core.Core(unicode(options.core_username), 
                                   config_instance)
  
  server_config_file = ConfigParser.SafeConfigParser()
  server_config_file.read(options.config_file)	

  versions = []
  if( len(core_instance.ListDnsServers()) == 0 ):
    print 'No DNS servers registered to check'
    sys.exit(1)

  for dns_server in core_instance.ListDnsServers():
    version_string = CheckBINDVersion(options.ssh_port, options.ssh_id,
        options.ssh_username, dns_server)

    versions.append(version_string)
    print '%s is running BIND %s' % (dns_server, version_string)

  if( len(set(versions)) > 1 ):
    print 'All servers are NOT running the same version of BIND'
  else:
    print 'All servers are running the same version of BIND'

if __name__ == "__main__":
    main(sys.argv[1:])
